package com.dwx.gmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dwx.gmall.model.product.BaseAttrInfo;
import com.dwx.gmall.model.product.BaseAttrValue;
import com.dwx.gmall.product.mapper.BaseAttrInfoMapper;
import com.dwx.gmall.product.mapper.BaseAttrValueMapper;
import com.dwx.gmall.product.service.BaseAttrInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class BaseAttrInfoServiceImpl extends ServiceImpl<BaseAttrInfoMapper, BaseAttrInfo> implements BaseAttrInfoService {

    @Autowired
    BaseAttrValueMapper baseAttrValueMapper;
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveInfoAndValue(BaseAttrInfo baseAttrInfo) {
        baseMapper.insert(baseAttrInfo);
        Long id = baseAttrInfo.getId();
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        if(!CollectionUtils.isEmpty(attrValueList)){
            for (BaseAttrValue baseAttrValue : attrValueList) {
                baseAttrValue.setAttrId(id);
                baseAttrValueMapper.insert(baseAttrValue);
            }
        }
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateInfoAndValue(BaseAttrInfo baseAttrInfo) {
        baseMapper.updateById(baseAttrInfo);
        Long id = baseAttrInfo.getId();
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();

        QueryWrapper<BaseAttrValue> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("attr_id",id);
        baseAttrValueMapper.delete(queryWrapper);

        for (BaseAttrValue baseAttrValue : attrValueList) {
            baseAttrValue.setAttrId(id);
            baseAttrValueMapper.insert(baseAttrValue);
        }
    }

    @Override
    public List<BaseAttrInfo> getAttrInfoList(Long category1Id, Long category2Id, Long category3Id) {

        return baseMapper.getAttrInfoList(category1Id, category2Id,category3Id);
    }

    @Override
    public void saveOrUpdateInfoAndValue(BaseAttrInfo baseAttrInfo) {
        if(baseAttrInfo.getId()==null){
            saveInfoAndValue(baseAttrInfo);
        }else {
            updateInfoAndValue(baseAttrInfo);
        }
    }
}
